package com.diary.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.diary.common.constant.MessageConstant;
import com.diary.common.context.BaseContext;
import com.diary.common.exception.LoginFailedException;
import com.diary.common.properties.WeChatProperties;
import com.diary.common.utils.HttpClientUtil;
import com.diary.server.dto.LoginDTO;
import com.diary.server.entity.User;
import com.diary.server.mapper.UserMapper;
import com.diary.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxLogin(LoginDTO userLoginDTO) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.getByOpenid(openid);
        if(user == null){
            user = User.builder().openId(openid).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }
        BaseContext.setCurrentId(user.getId());
        log.info("当前用户id为：{}",BaseContext.getCurrentId());

        return user;
    }


}
